package com.example.calendar.data.local.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.example.calendar.data.model.Category
import com.example.calendar.data.model.CategoryType
import kotlinx.coroutines.flow.Flow
import org.threeten.bp.LocalDateTime

@Dao
interface CategoryDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCategory(category: Category): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCategories(categories: List<Category>): List<Long>

    @Update
    suspend fun updateCategory(category: Category)

    @Delete
    suspend fun deleteCategory(category: Category)

    @Query("UPDATE categories SET isDeleted = 1, updatedAt = :now WHERE id = :categoryId")
    suspend fun softDeleteCategory(categoryId: String, now: LocalDateTime = LocalDateTime.now())

    @Query("SELECT * FROM categories WHERE id = :categoryId AND isDeleted = 0")
    fun getCategoryById(categoryId: String): Flow<Category?>

    @Query("SELECT * FROM categories WHERE isDeleted = 0 ORDER BY name ASC")
    fun getAllCategories(): Flow<List<Category>>

    @Query("SELECT * FROM categories WHERE isDeleted = 0 AND type IN (:types) ORDER BY name ASC")
    fun getCategoriesByType(types: List<CategoryType>): Flow<List<Category>>

    @Query("SELECT * FROM categories WHERE isDeleted = 0 AND (type = :type OR type = :bothType) ORDER BY name ASC")
    fun getCategoriesByType(type: CategoryType, bothType: CategoryType = CategoryType.BOTH): Flow<List<Category>>

    @Query("SELECT * FROM categories WHERE isDeleted = 0 AND isDefault = 1 AND type = :type LIMIT 1")
    fun getDefaultCategoryForType(type: CategoryType): Flow<Category?>
} 